import {
    AJAX_CODE_SUCCESS,
    AJAX_CODE_ERROR,
    AJAX_CODE_WARNING,
    AJAX_CODE_LOGIN,
    NO_PERMISSION
} from 'constants';

import {message} from 'antd';
import config from 'config';
import {redirect,getCookie} from 'lib/utils';
import store from '../store';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from  'react-router-redux';


export const API_PREFIX = config.API_PREFIX;


const history = syncHistoryWithStore(browserHistory,store);

export const LOGIN = "/login"; //登录
export const LOGOUT = "/logout"; //登出
export const SET_FIELD = "/setField"; //设置列表字段
export const CLEAR_CACHE = "/admin/clearCache";//清除缓存
export const GET_MENU  = "/getMenus"; //获取菜单栏
export const GET_CSRF_TOKEN = "/getCsrfToken";
export const OSS_UPLOAD = "/ossUpload";

//管理员
export const GET_USER_INFO = "/getUserInfo"; //获取当前管理员信息
export const GET_ADMIN_LIST = "/getAdminList"; //管理员列表
export const GET_ADMIN_PRIVS = "/getAdminPrivs";//获取管理员列表权限
export const EDIT_ADMIN = "/editAdmin" ; //编辑管理员
export const SAVE_ADMIN = "/storeAdmin"; //保存管理员
//权限组
export const GET_ROLE_PRIVS = "/getRolePrivs"; //获取权限操作权限
export const GET_ALL_ROLE = "/getAllRole"; //获取所有角色
export const GET_ALL_PRIVS = "/getAllPrivs"; //获取所有权限
export const EDIT_ROLE = "/editRole"; //编辑角色
export const GET_ROLE_LIST = "/getRoleList"; //权限组列表
export const SAVE_ROLE = "/saveRole";   //保存

//商家用户
export const GET_MERCHANT_LIST = "/getMerchantList";
export const GET_MERCHANT_PRIVS  = '/getMerchantPrivs';
export const EDIT_MERCHANT = "/editMerchant";
export const SAVE_MERCHANT = '/saveMerchant';

//应用
export const GET_APP_LIST ='/getAppList';
export const GET_APP_PRIVS = '/getAppPrivs';
export const EDIT_APP = '/editApp';
export const SAVE_APP = '/saveApp';

export const GET_ALL_APP_CATE = '/getAllAppCate';


let xhrPool = [];


export default {
    get(url, params, cb, errorCb){
        this.send(url, 'GET', params, cb, errorCb);
    },
    post(url, params, cb, errorCb) {
        this.send(url, 'POST', params, cb, errorCb);
    },
    fetch(config, param, cb, errorCb){
        if (typeof config === "string") {
            this.get(config, param, cb, errorCb)
        } else {
            const {method} = config;
            this.send(config.url, method || "POST", param, cb, errorCb);
        }
    },
    send(url, method, params, cb, errorCb) {

        const xhr = new XMLHttpRequest();
        xhrPool.push(xhr);
        let newUrl = API_PREFIX + url;
        let body;
        if (params) {
            let bodies = [];
            for (let name in params) {
                if (params.hasOwnProperty(name)) {
                    bodies.push(name + '=' + encodeURIComponent(params[name]));
                }
            }
            body = bodies.join('&');
            if (method === "GET") {
                newUrl = newUrl + "?" + body;
            }
        }
        xhr.open(method, newUrl, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                xhrPool.splice(xhrPool.indexOf(xhr), 1);
                if (xhrPool.length === 0) {

                    // Loading.hide();
                }
                let data = xhr.responseText;
                try {
                    data = JSON.parse(data);
                } catch (exc) {
                }
                if (cb) {
                    if (typeof data === "object") {
                        if (data.c === AJAX_CODE_LOGIN) {
                            window.location.href = "/login";
                        } else if (data.c === AJAX_CODE_SUCCESS) {
                            return cb(data.d);
                        } else if (data.c === AJAX_CODE_ERROR) {
                            return errorCb ? errorCb(data) : message.error(data.m);
                        }else if(data.c === NO_PERMISSION){
                            history.push("/m");
                        } else {
                            errorCb ? errorCb(data) : message.error(data.m);
                        }
                    }
                    else {
                        errorCb ? errorCb(data) : message.error(data.m);
                    }
                }
            }
        };
        xhr.setRequestHeader("Accept", "application/json;charset=utf-8");

        if (body.length) {
            let header = "application/x-www-form-urlencoded";
            xhr.setRequestHeader("Content-type", header);
        }
        xhr.send(body);
    }
};


